package com.newx.web.service;

import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.newx.common.core.constant.Constants;
import com.newx.common.core.constant.GlobalConstants;
import com.newx.common.core.domain.model.RegisterBody;
import com.newx.common.core.enums.UserType;
import com.newx.common.core.exception.user.CaptchaException;
import com.newx.common.core.exception.user.CaptchaExpireException;
import com.newx.common.core.exception.user.UserException;
import com.newx.common.core.utils.GeneratorNoUtils;
import com.newx.common.core.utils.MessageUtils;
import com.newx.common.core.utils.ServletUtils;
import com.newx.common.core.utils.SpringUtils;
import com.newx.common.core.utils.ip.RegionUtils;
import com.newx.common.log.event.LoginEvent;
import com.newx.common.redis.utils.RedisUtils;
import com.newx.common.tenant.helper.TenantHelper;
import com.newx.common.web.config.properties.CaptchaProperties;
import com.newx.system.domain.SysUser;
import com.newx.system.domain.bo.SysUserBo;
import com.newx.system.mapper.SysUserMapper;
import com.newx.system.service.ISysUserService;
import com.newx.web.events.RegisterEvent;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 注册校验方法
 *
 * @author Lion Li
 */
@RequiredArgsConstructor
@Service
public class SysRegisterService {

    private final ISysUserService userService;
    private final SysUserMapper userMapper;
    private final CaptchaProperties captchaProperties;

    /**
     * 注册
     */
    public Long register(RegisterBody registerBody, HttpServletRequest request) {
        String tenantId = registerBody.getTenantId();
        String username = registerBody.getUsername();
        String password = registerBody.getPassword();
        // 校验用户类型是否存在
        String userType = UserType.getUserType(registerBody.getUserType()).getUserType();

        String existsMessage = "";
        SysUserBo sysUser = new SysUserBo();
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();

        //授权类型 password | sms | email | address
        if (ObjectUtil.equal(registerBody.getGrantType(), "password")) {
            if (StringUtils.isBlank(username)) {
                throw new UserException(MessageUtils.message("user.username.not.blank"));
            }
            existsMessage = username;
            wrapper.eq(SysUser::getUserName, registerBody.getUsername());
        }

        //短信注册
        if (ObjectUtil.equal(registerBody.getGrantType(), "sms")) {
            if (StringUtils.isBlank(registerBody.getPhonenumber())) {
                throw new UserException(MessageUtils.message("user.phonenumber.not.blank"));
            }
            existsMessage = registerBody.getPhonenumber();
            wrapper.eq(SysUser::getPhonenumber, registerBody.getPhonenumber());
            validateCaptcha(tenantId, registerBody.getPhonenumber(), registerBody.getCode());
        }

        //邮箱注册
        if (ObjectUtil.equal(registerBody.getGrantType(), "email")) {
            if (StringUtils.isBlank(registerBody.getEmail())) {
                throw new UserException(MessageUtils.message("user.email.not.blank"));
            }
            existsMessage = registerBody.getEmail();
            wrapper.eq(SysUser::getEmail, registerBody.getEmail());
            validateCaptcha(tenantId, registerBody.getEmail(), registerBody.getCode());
        }

        //钱包注册
        if (ObjectUtil.equal(registerBody.getGrantType(), "address")) {
            if (StringUtils.isBlank(registerBody.getAddress())) {
                throw new UserException(MessageUtils.message("user.address.not.blank"));
            }
            existsMessage = registerBody.getAddress();
            wrapper.eq(SysUser::getUserName, registerBody.getAddress());
        }

        //校验是否唯一
        if (TenantHelper.dynamic(tenantId, () -> userMapper.exists(wrapper))) {
            throw new UserException("user.register.save.error", existsMessage);
        }

        sysUser.setNickName(registerBody.getNickName());
        sysUser.setPassword(BCrypt.hashpw(password));
        sysUser.setUserType(userType);
        sysUser.setEmail(registerBody.getEmail());
        sysUser.setPhonenumber(registerBody.getPhonenumber());
        sysUser.setUserName(username);
        sysUser.setUserId(GeneratorNoUtils.createNineNumber());
        sysUser.setUserUId(sysUser.getUserId());

        SysUserBo sysUserBo = userService.registerUser(sysUser, tenantId);
        if (Objects.isNull(sysUserBo.getUserId())) {
            throw new UserException("user.register.error");
        }

        RegisterEvent registerEvent = new RegisterEvent();
        registerEvent.setHost(request.getServerName());
        registerEvent.setActiveCode(registerBody.getActiveCode());
        registerEvent.setIp(RegionUtils.getIpAddr(request));
        registerEvent.setUserUId(sysUser.getUserUId());
        SpringUtils.context().publishEvent(registerEvent);
        recordLogininfor(tenantId, username, Constants.REGISTER, MessageUtils.message("user.register.success"));

        return sysUserBo.getUserId();
    }

    /**
     * 校验验证码
     *
     * @param username 注册方式
     * @param code     验证码
     */
    public void validateCaptcha(String tenantId, String username, String code) {
        String verifyKey = GlobalConstants.CAPTCHA_CODE_KEY + username;
        String captcha = RedisUtils.getCacheObject(verifyKey);
        if (captcha == null) {
            recordLogininfor(tenantId, username, Constants.REGISTER, MessageUtils.message("user.jcaptcha.expire"));
            throw new CaptchaExpireException();
        }
        if (!captcha.equalsIgnoreCase(code)) {
            recordLogininfor(tenantId, username, Constants.REGISTER, MessageUtils.message("user.jcaptcha.error"));
            throw new CaptchaException();
        }
        RedisUtils.deleteObject(verifyKey);
    }

    /**
     * 记录登录信息
     *
     * @param tenantId 租户ID
     * @param username 用户名
     * @param status   状态
     * @param message  消息内容
     * @return
     */
    private void recordLogininfor(String tenantId, String username, String status, String message) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setTenantId(tenantId);
        loginEvent.setUsername(username);
        loginEvent.setStatus(status);
        loginEvent.setMessage(message);
        loginEvent.setRequest(ServletUtils.getRequest());
        SpringUtils.context().publishEvent(loginEvent);
    }

}
